package com.yx.system.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.yx.common.annotation.Log;
import com.yx.common.annotation.LoginUser2;
import com.yx.common.utils.DateUtils;
import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.common.validator.Assert;
import com.yx.modules.api.entity.TbVolume;
import com.yx.modules.api.service.TbVolumeService;
import com.yx.system.dto.BookFileDto;
import com.yx.system.entity.*;
import com.yx.system.service.TdBookService;
import com.yx.system.service.TdSectionService;
import com.yx.system.service.impl.TdTextServiceImpl;
import com.yx.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 章节控制器
 */
@RestController
@RequestMapping("/sys/section")
public class TdSectionController2 {

    Logger logger = LoggerFactory.getLogger(TdSectionController2.class);

    @Autowired
    private TdSectionService tdSectionService;

    @Autowired
    private TdTextServiceImpl tdTextService;

    @Autowired
    private TdBookService tdBookService;

    @Autowired
    private TbVolumeService tbVolumeService;

    /**
     * 按ID查询
     *
     * @return
     */
    @Log("按ID查询")
    @RequestMapping("/findById/{id}")
    @RequiresPermissions("sys:section:findById")
    public R findById(@PathVariable("id") int id) {
        Map<String, Object> map = new HashMap<>();
        TdSection tdSection = tdSectionService.findByIdAndAuthor(id);
        map.put("section", tdSection);
        return R.ok().put("map", map);
    }





    /*
    * 管理员批量上传图书
    */
    @RequestMapping("put")
    public R put(List<BookFileDto> bookFileDtos,@LoginUser2 SysUser sysUser) throws IOException {
        String regex = "[\\u4e00-\\u9fa5]|[\\，\\。\\.]";
        String regex2 = "[宋体]|[黑体]|[微软雅黑]|[楷体]";
//        List<BookFileDto> bookFileDtos = HttpUtil.jsonToList(arr,BookFileDto.class);
        if (bookFileDtos.size()!=0){
            for (BookFileDto bookFileDto:bookFileDtos){
                MultipartFile filetext = bookFileDto.getFile();
                String sectionname = bookFileDto.getSectionname();
                Integer bookid = bookFileDto.getBookid();
                String bookPrice = bookFileDto.getBookPrice();
                Integer volumeId = bookFileDto.getVolumeId();
                if (volumeId.equals("")){
                    return R.error("请选择所属卷");
                }
                TdSection tdSection = new TdSection();
                if (Integer.parseInt(AmountUtils.changeY2F(bookPrice))!=0){
                    tdSection.setSectionType(1);
                }else {
                    tdSection.setSectionType(0);
                }
                //根据volumeId查询卷
                TbVolume tbVolume = tbVolumeService.queryObject(volumeId);
                tdSection.setBookid(bookid);
                tdSection.setCreatedate(new Date());
                tdSection.setIsdelete(false);
                tdSection.setVolumeId(tbVolume.getId());
                tdSection.setVolumeName(tbVolume.getVolumeName());
                tdSection.setCreateuser(sysUser.getUsername());
                tdSection.setUpdatedate(new Date());
                tdSection.setSectionStatus(0);
                tdSection.setUpdateuser(sysUser.getUsername());
                tdSection.setTotalfee(Integer.parseInt(AmountUtils.changeY2F(bookPrice)));
                tdSection.setSectionname(sectionname);
                tdSection.setSectionno((int) Math.random());
                tdSection.setUuid(UidUtil.getUUID());
                int tdSectionId = tdSectionService.insert(tdSection);
                tdSectionService.selectByPrimaryKey(tdSectionId);
                //查询书籍信息
                TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
                tdBook.setUpdatedate(new Date());
                tdBook.setNewsection(tdSection.getSectionname());
                tdBook.setNewsectionid(tdSection.getId());
                tdBook.setSectionNumber(tdBook.getSectionNumber()+1);
                if (tdSection.getTotalfee()>0){
                    tdBook.setIspay(true);
                }
                tdBookService.updateByPrimaryKey(tdBook);
                //实例文本对象，并赋值
                TdText tdText = new TdText();
                tdText.setAuthor(tdBook.getAuthorName());
                tdText.setBookname(tdBook.getBookname());
                tdText.setCreatetime(new Date());
                tdText.setIsdelete(0);
                tdText.setUid(tdSection.getUuid());
                tdText.setSection(tdSection.getSectionname());
//          读取文件中得内容，并且赋值给文本对象
                tdText.setText(ContextUtil.fileReadUtil(filetext));
                tdText.setId(UidUtil.getUUID());
                int count1 =(" " + ContextUtil.fileReadUtil(filetext) + " ").split (regex).length - 1;
                int count2 = (" " + ContextUtil.fileReadUtil(filetext) + " ").split (regex2).length - 1;
                int count = count1>count2?(count1-count2):count1;
                //执行保存操作
                tdTextService.saveText(tdText);
                tdSection.setFontsize(count);
                tdSectionService.updateByPrimaryKey(tdSection);
            }
        }
        return R.ok();
    }



    /**
     * 新增或修改图书
     *
     * @return
     */
    @PostMapping("save")
    @RequiresPermissions("sys:section:save")
    public R saveOrUpdate(String id, MultipartFile filetext, String sectionname, Integer bookid, String bookPrice, Integer volumeId,@LoginUser2 SysUser sysUser) throws IOException {
        Assert.isBlank(sectionname,"请输入章节名");
        if (volumeId.equals("") && volumeId==null){
            return R.error("请选择所属卷");
        }
        if (sysUser.getIdentity()==1 && Integer.parseInt(AmountUtils.changeY2F(bookPrice))>0){
            return R.error("签约作者才能收费");
        }
        TdSection tdSection = new TdSection();
        if (Integer.parseInt(AmountUtils.changeY2F(bookPrice))!=0){
            tdSection.setSectionType(1);
        }else {
            tdSection.setSectionType(0);
        }
        String regex = "[\\u4e00-\\u9fa5]|[\\，\\。\\.]";
        String regex2 = "[宋体]|[黑体]|[微软雅黑]|[楷体]";
        //根据volumeId查询卷
        TbVolume tbVolume = tbVolumeService.queryObject(volumeId);
        if (id.equals("")) {
            tdSection.setBookid(bookid);
            tdSection.setCreatedate(new Date());
            tdSection.setIsdelete(false);
            tdSection.setVolumeId(tbVolume.getId());
            tdSection.setVolumeName(tbVolume.getVolumeName());
            tdSection.setCreateuser(sysUser.getUsername());
            tdSection.setUpdatedate(new Date());
            tdSection.setSectionStatus(0);
            tdSection.setUpdateuser(sysUser.getUsername());
            tdSection.setTotalfee(Integer.parseInt(AmountUtils.changeY2F(bookPrice)));
            tdSection.setSectionname(sectionname);
            tdSection.setSectionno((int) Math.random());
            tdSection.setUuid(UidUtil.getUUID());
            int tdSectionId = tdSectionService.insert(tdSection);
            tdSectionService.selectByPrimaryKey(tdSectionId);
            //查询书籍信息
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            tdBook.setNewsection(tdSection.getSectionname());
            tdBook.setNewsectionid(tdSection.getId());
            tdBook.setSectionNumber(tdBook.getSectionNumber()+1);
            tdBook.setUpdatedate(new Date());
            if (tdSection.getTotalfee()>0){
                tdBook.setIspay(true);
            }
            tdBookService.updateByPrimaryKey(tdBook);
            //实例文本对象，并赋值
            TdText tdText = new TdText();
            tdText.setAuthor(tdBook.getAuthorName());
            tdText.setBookname(tdBook.getBookname());
            tdText.setCreatetime(new Date());
            tdText.setIsdelete(0);
            tdText.setUid(tdSection.getUuid());
            tdText.setSection(tdSection.getSectionname());
//          读取文件中得内容，并且赋值给文本对象
            tdText.setText(ContextUtil.fileReadUtil(filetext));
            tdText.setId(UidUtil.getUUID());
            int count =(" " + ContextUtil.fileReadUtil(filetext) + " ").split (regex).length - 1;
            //执行保存操作
            tdTextService.saveText(tdText);
            tdSection.setFontsize(count);
            tdSectionService.updateByPrimaryKey(tdSection);
        } else {
            tdSection = tdSectionService.selectByPrimaryKey(Integer.parseInt(id));
            tdSection.setVolumeId(tbVolume.getId());
            tdSection.setVolumeName(tbVolume.getVolumeName());
            tdSection.setBookid(bookid);
            tdSection.setUpdatedate(new Date());
            tdSection.setUpdateuser(sysUser.getUsername());
            tdSection.setTotalfee(Integer.parseInt(AmountUtils.changeY2F(bookPrice)));
            tdSection.setSectionname(sectionname);
            tdSection.setSectionStatus(0);
            tdSection.setSectionno((int) Math.random());
            tdSectionService.updateByPrimaryKey(tdSection);
            //查询书籍信息
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            if (filetext != null && !filetext.equals("")) {
                //获取文件上传后的访问地址
                TdText tdText = null;
                tdText = tdTextService.findByInfo(tdSection.getUuid());
                //实例文本对象，并赋值
                tdText.setAuthor(tdBook.getAuthorName());
                tdText.setBookname(tdBook.getBookname());
                tdText.setCreatetime(new Date());
                tdText.setIsdelete(0);
                tdText.setUid(tdSection.getUuid());
                tdText.setSection(tdSection.getSectionname());
                //将上传后的文件传入文件对象
                //读取文件中得内容，并且赋值给文本对象
                tdText.setText(ContextUtil.fileReadUtil(filetext));
                int count1 =(" " + ContextUtil.fileReadUtil(filetext) + " ").split (regex).length - 1;
                int count2 = (" " + ContextUtil.fileReadUtil(filetext) + " ").split (regex2).length - 1;
                int count = count1>count2?(count1-count2):count1;
                //执行更新操作
                tdTextService.updateText(tdText);
                tdSection.setFontsize(count);
                tdSectionService.updateByPrimaryKey(tdSection);
            }
        }
        TdBook book = tdBookService.selectByPrimaryKey(tdSection.getBookid());
        List<TdSection> tdSections = tdSectionService.findByBookid(book.getId());
        book.setSectionNumber(tdSections.size());
        tdBookService.updateByPrimaryKey(book);
        return R.ok();
    }

    /*
    *
    */
    /*@Log("作者写书")
    @RequestMapping("saveByAuthor")
    @RequiresPermissions("sys:section:saveByAuthor")
    public R saveByAuthor(String text1,String sectionname, Integer bookid, String bookPrice, Integer volumeId,@LoginUser2 SysUser sysUser) throws UnsupportedEncodingException {

        Assert.isBlank(text1,"内容不能为空");
        Assert.isBlank(bookPrice,"价格不能为空");
        Assert.isBlank(sectionname,"章节名不能为空");
        Assert.isNull(bookid,"图书标识不能为空");
        Assert.isNull(volumeId,"章节所属分类不能为空");
        String text=new String(Base64.decodeBase64(text1),"utf-8");
        if (sysUser.getIdentity()==1 && Integer.parseInt(AmountUtils.changeY2F(bookPrice))>0){
            return R.error("签约作者才能收费");
        }
        TdSection tdSection = new TdSection();
        if (Integer.parseInt(AmountUtils.changeY2F(bookPrice))!=0){
            tdSection.setSectionType(1);
        }else {
            tdSection.setSectionType(0);
        }
        String regex = "[\u4e00-\u9fff]";
        //根据volumeId查询卷
        TbVolume tbVolume = tbVolumeService.queryObject(volumeId);
        tdSection.setBookid(bookid);
        tdSection.setCreatedate(new Date());
        tdSection.setIsdelete(false);
        tdSection.setVolumeId(tbVolume.getId());
        tdSection.setVolumeName(tbVolume.getVolumeName());
        tdSection.setCreateuser(sysUser.getUsername());
        tdSection.setUpdatedate(new Date());
        tdSection.setUpdateuser(sysUser.getUsername());
        tdSection.setTotalfee(Integer.parseInt(AmountUtils.changeY2F(bookPrice)));
        tdSection.setSectionname(sectionname);
        tdSection.setSectionno((int) Math.random());
        tdSection.setUuid(UidUtil.getUUID());
        int tdSectionId = tdSectionService.insert(tdSection);
        tdSectionService.selectByPrimaryKey(tdSectionId);
        //查询书籍信息
        TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
        tdBook.setNewsection(tdSection.getSectionname());
        tdBook.setNewsectionid(tdSection.getId());
        if (tdSection.getTotalfee()>0){
            tdBook.setIspay(true);
        }
        tdBookService.updateByPrimaryKey(tdBook);
        //实例文本对象，并赋值
        TdText tdText = new TdText();
        tdText.setAuthor(tdBook.getAuthorName());
        tdText.setBookname(tdBook.getBookname());
        tdText.setCreatetime(new Date());
        tdText.setIsdelete(0);
        tdText.setUid(tdSection.getUuid());
        tdText.setSection(tdSection.getSectionname());
        //读取文件中得内容，并且赋值给文本对象
        tdText.setText(text);
        tdText.setId(UidUtil.getUUID());
        int count =(" " + text + " ").split (regex).length - 1;
        //执行保存操作
        tdTextService.saveText(tdText);
        tdSection.setFontsize(count);
        tdSectionService.updateByPrimaryKey(tdSection);
        return R.ok();
    }*/



    /*
    *
    */
    @RequestMapping("saveByAuthor")
    @RequiresPermissions("sys:section:saveByAuthor")
    public R saveByAuthor(String text1,String sectionname, Integer bookid,Integer volumeId,String leadStr,String publishTime,@LoginUser2 SysUser sysUser) throws UnsupportedEncodingException, ParseException {
        System.out.println("===================================进入作者添加章节==========================================");
        System.out.println("===================================内容=========================================="+text1);
        System.out.println("===================================章节名称=========================================="+sectionname);
        System.out.println("===================================图书id=========================================="+bookid);
        System.out.println("===================================卷id=========================================="+volumeId);
        System.out.println("===================================引导语=========================================="+leadStr);
        System.out.println("===================================发布时间=========================================="+publishTime);
        Assert.isBlank(text1,"内容不能为空");
        Assert.isBlank(sectionname,"章节名不能为空");
        Assert.isNull(bookid,"图书标识不能为空");
        Assert.isNull(volumeId,"章节所属分类不能为空");
        String regex = "[\\u4e00-\\u9fa5]|[\\，\\。\\.]";
        String regex2 = "[宋体]|[黑体]|[微软雅黑]|[楷体]";
        if (publishTime.equals("")){
            System.out.println("===================================第一步==========================================");
            String text = new String(Base64.decodeBase64(text1),"utf-8");
            String lead = new String(Base64.decodeBase64(leadStr),"utf-8");
            String content = text + lead;
            TdSection tdSection = new TdSection();
            //根据volumeId查询卷
            TbVolume tbVolume = tbVolumeService.queryObject(volumeId);
            tdSection.setSectionType(0);
            tdSection.setBookid(bookid);
            tdSection.setCreatedate(new Date());
            tdSection.setIsdelete(false);
            tdSection.setVolumeId(tbVolume.getId());
            tdSection.setVolumeName(tbVolume.getVolumeName());
            tdSection.setCreateuser(sysUser.getUsername());
            tdSection.setUpdatedate(new Date());
            tdSection.setUpdateuser(sysUser.getUsername());
            tdSection.setTotalfee(0);
            tdSection.setSectionname(sectionname);
            tdSection.setSectionno((int) Math.random());
            tdSection.setUuid(UidUtil.getUUID());
            tdSection.setSectionStatus(0);
            tdSection.setContext(text);
            tdSection.setLead(lead);
            System.out.println("===================================第二步==========================================");
            //找到当前章节添加之前的最后一章
            List<TdSection> tdSections = tdSectionService.findByBookidToCharge(bookid);

            int tdSectionId = tdSectionService.insert(tdSection);
            tdSectionService.selectByPrimaryKey(tdSectionId);
            //查询书籍信息
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            tdBook.setNewsection(tdSection.getSectionname());
            tdBook.setNewsectionid(tdSection.getId());
            tdBook.setUpdatedate(new Date());
            tdBook.setSectionNumber(tdBook.getSectionNumber()+1);
            System.out.println("===================================第三步==========================================");
            if (tdSection.getTotalfee()>0){
                tdBook.setIspay(true);
            }else {
                tdBook.setIspay(false);
            }
            tdBookService.updateByPrimaryKey(tdBook);
            //实例文本对象，并赋值
            TdText tdText = new TdText();
            tdText.setAuthor(tdBook.getAuthorName());
            tdText.setBookname(tdBook.getBookname());
            tdText.setCreatetime(new Date());
            tdText.setIsdelete(0);
            tdText.setUid(tdSection.getUuid());
            tdText.setSection(tdSection.getSectionname());
            //读取文件中得内容，并且赋值给文本对象
            tdText.setText(content);
            tdText.setId(UidUtil.getUUID());
            int count1 =(" " + text + " ").split (regex).length - 1;
            int count2 = (" " + text + " ").split (regex2).length - 1;
            int count = count1>count2?(count1-count2):count1;
            //执行保存操作
            tdTextService.saveText(tdText);
            System.out.println("===================================第四步==========================================");
            tdSection.setFontsize(count);
            if (tdSections.size()!=0){
                //取得最后一章
                TdSection tdSectionLast = tdSections.get(tdSections.size()-1);
                //根据最后的章节来判断是否收费
                if (tdSectionLast.getTotalfee()>0){
                    //算出收费比例
                    //取得章节字数
                    Double lastFont = Double.valueOf(tdSectionLast.getFontsize());
                    //四舍五入保留两位小数
                    BigDecimal bg = new BigDecimal(lastFont/1000);
                    Double lastFontSize = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    Integer lastTotalfee = tdSectionLast.getTotalfee();
                    //价格除以千字数的出定价
                    Double priceRation = lastTotalfee/lastFontSize;
                    //取出现在章节的字数千数
                    Double font = Double.valueOf(tdSection.getFontsize());
                    //四舍五入保留两位小数
                    BigDecimal bgNow = new BigDecimal(font/1000);
                    Double fontSize = bgNow.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    //算出新的章节价格
                    int price = (int) (fontSize*priceRation);
                    //存入价格
                    tdSection.setTotalfee(price);
                    tdSection.setSectionType(1);
                }
            }
            tdSectionService.updateByPrimaryKey(tdSection);
            //计算图书字数
            List<TdSection> sections = tdSectionService.findByBookid(tdBook.getId());
            if (sections.size()!=0){
                int sum = 0;
                for (TdSection tdSection1:sections){
                    sum += tdSection1.getFontsize();
                }
                tdBook.setFontCount(sum);
                tdBookService.updateByPrimaryKey(tdBook);
            }
        }else {
            String text = new String(Base64.decodeBase64(text1),"utf-8");
            String lead = new String(Base64.decodeBase64(leadStr),"utf-8");
            TdSection tdSection = new TdSection();
            TbVolume tbVolume = tbVolumeService.queryObject(volumeId);
            tdSection.setSectionStatus(1);
            tdSection.setSectionType(0);
            int count1 =(" " + text + " ").split (regex).length - 1;
            int count2 = (" " + text + " ").split (regex2).length - 1;
            int count = count1>count2?(count1-count2):count1;
            tdSection.setFontsize(count);
            tdSection.setVolumeName(tbVolume.getVolumeName());
            tdSection.setVolumeId(tbVolume.getId());
            tdSection.setIsdelete(false);
            tdSection.setBookid(bookid);
            tdSection.setTotalfee(0);
            tdSection.setCreatedate(new Date());
            tdSection.setCreateuser(sysUser.getUsername());
            tdSection.setUpdatedate(new Date());
            tdSection.setUpdateuser(sysUser.getUsername());
            tdSection.setSectionname(sectionname);
            tdSection.setSectionno((int) Math.random());
            tdSection.setUuid(UidUtil.getUUID());
            tdSection.setPublishDate(DateUtils.format2(publishTime));
            tdSection.setContext(text);
            tdSection.setLead(lead);
            //找到当前章节添加之前的最后一章
            List<TdSection> tdSections = tdSectionService.findByBookidToCharge(bookid);
            if (tdSections.size()!=0){
                //取得最后一章
                TdSection tdSectionLast = tdSections.get(tdSections.size()-1);
                //根据最后的章节来判断是否收费
                if (tdSectionLast.getTotalfee()>0){
                    //算出收费比例
                    //取得章节字数
                    Double lastFont = Double.valueOf(tdSectionLast.getFontsize());
                    //四舍五入保留两位小数
                    BigDecimal bg = new BigDecimal(lastFont/1000);
                    Double lastFontSize = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    Integer lastTotalfee = tdSectionLast.getTotalfee();
                    //价格除以千字数的出定价
                    Double priceRation = lastTotalfee/lastFontSize;
                    //取出现在章节的字数千数
                    Double font = Double.valueOf(tdSection.getFontsize());
                    //四舍五入保留两位小数
                    BigDecimal bgNow = new BigDecimal(font/1000);
                    Double fontSize = bgNow.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    //算出新的章节价格
                    int price = (int) (fontSize*priceRation);
                    //存入价格
                    tdSection.setTotalfee(price);
                    tdSection.setSectionType(1);
                }
            }
            tdSectionService.insert(tdSection);
            //计算图书字数
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            List<TdSection> sections = tdSectionService.findByBookid(tdBook.getId());
            if (sections.size()!=0){
                int sum = 0;
                for (TdSection tdSection1:sections){
                    sum += tdSection1.getFontsize();
                }
                tdBook.setFontCount(sum);
                tdBookService.updateByPrimaryKey(tdBook);
            }
        }
        return R.ok();
    }
    /*
     * 作者修改图书
     */
    @PostMapping("update")
    @RequiresPermissions("sys:section:save")
    public R update(Integer id,String text1,String sectionname, Integer bookid,@LoginUser2 SysUser sysUser) throws IOException {
        Assert.isBlank(text1,"内容不能为空");
        Assert.isBlank(sectionname,"章节名不能为空");
        Assert.isNull(bookid,"图书标识不能为空");
        String regex = "[\\u4e00-\\u9fa5]|[\\，\\。\\.]";
        String regex2 = "[宋体]|[黑体]|[微软雅黑]|[楷体]";
        //先根据id查询到此章节
        TdSection tdSection = tdSectionService.findByIdAndAuthor(id);
        if (tdSection==null){
            return R.error("查询章节时出现未知错误，操作失败");
        }
        String text = new String(Base64.decodeBase64(text1),"utf-8");
        //即时发布
        if (tdSection.getSectionStatus()==0){
            String content = text+tdSection.getLead();
            tdSection.setContext(text);
            tdSection.setSectionname(sectionname);
            tdSection.setUpdateuser(sysUser.getUsername());
            tdSection.setUpdatedate(new Date());
            int count1 =(" " + text + " ").split (regex).length - 1;
            int count2 = (" " + text + " ").split (regex2).length - 1;
            int count = count1>count2?(count1-count2):count1;
            tdSection.setFontsize(count);
            tdSectionService.updateByPrimaryKey(tdSection);
            //根据章节去寻找Text。
            TdText tdText = tdTextService.findByInfo(tdSection.getUuid());
            if (tdText==null){
                return R.error("查询章节内容时出现未知错误，操作失败");
            }
            tdText.setText(content);
            tdTextService.updateText(tdText);
            //计算图书字数
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            List<TdSection> sections = tdSectionService.findByBookid(tdBook.getId());
            if (sections.size()!=0){
                int sum = 0;
                for (TdSection tdSection1:sections){
                    sum += tdSection1.getFontsize();
                }
                tdBook.setFontCount(sum);
                tdBook.setUpdatedate(new Date());
                tdBookService.updateByPrimaryKey(tdBook);
            }
        //定时发布
        }else {
            tdSection.setContext(text);
            tdSection.setSectionname(sectionname);
            tdSection.setUpdateuser(sysUser.getUsername());
            tdSection.setUpdatedate(new Date());
            int count1 =(" " + text + " ").split (regex).length - 1;
            int count2 = (" " + text + " ").split (regex2).length - 1;
            int count = count1>count2?(count1-count2):count1;
            tdSection.setFontsize(count);
            tdSectionService.updateByPrimaryKey(tdSection);
            //计算图书字数
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            List<TdSection> sections = tdSectionService.findByBookid(tdBook.getId());
            if (sections.size()!=0){
                int sum = 0;
                for (TdSection tdSection1:sections){
                    sum += tdSection1.getFontsize();
                }
                tdBook.setFontCount(sum);
                tdBook.setUpdatedate(new Date());
                tdBookService.updateByPrimaryKey(tdBook);
            }
        }
        return R.ok();

    }

    /**
     * 删除(软删除)
     *
     * @return
     */
    @Log("删除章节(软删除)")
    @PostMapping("delete")
    @RequiresPermissions("sys:section:delete")
    public R delete(@RequestBody Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            int id = ids[i];
            TdSection tdSection = tdSectionService.selectByPrimaryKey(id);
            if (tdSection!=null){
                tdSection.setIsdelete(true);
                tdSectionService.updateByPrimaryKey(tdSection);
            }
        }
        return R.ok();
    }

    /**
     * 查询所有
     *
     * @param map
     * @return
     */
    @Log("查询所有")
    @PostMapping("findAllByCondition")
    @RequiresPermissions("sys:section:findAllByCondition")
    public R findAllByCondition(@RequestParam Map<String, Object> map) {
        Query query = new Query(map);
        Page<TdSection> pageUtil = new Page<TdSection>(query.getPage(), query.getLimit());
        Page<TdSection> page = tdSectionService.queryPageList2(pageUtil, query);
        return R.ok().put("page", page);
    }

    public static void main(String[] args){

    }


    }
